package com.cloud.wx.util;

import cn.hutool.core.convert.Convert;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.cloud.redis.config.RedisUtils;
import com.cloud.wx.config.WxConfig;
import com.cloud.wx.model.enums.RedisKey;
import com.cloud.wx.model.enums.WxConst;
import com.cloud.wx.model.response.AccessTokenResponse;
import com.cloud.wx.model.response.TokenResponse;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@AllArgsConstructor
@Service
public class TokenService {
    private final WxConfig wxConfig;
    private final RedisUtils redisUtils;

    public String getToken() {
        String key = RedisKey.tokenKey;
        Object o = redisUtils.get(key);
        String token = "";
        if (null == o) {
            String resp = HttpUtil.get(WxConst.wxServiceUrl + "cgi-bin/token?grant_type=client_credential&appid=" + wxConfig.getAppid() + "&secret=" + wxConfig.getAppsecret());
            if (resp.contains("expires_in")) {
                //如果不存在过期时间，说明返回值有问题
                TokenResponse tokenResponse = JSONUtil.toBean(resp, TokenResponse.class);
                token = tokenResponse.getAccess_token();
                redisUtils.set(key, token);
                return token;
            }
        } else {
            token = Convert.toStr(o);
        }
        return token;
    }

//    第二步：通过code换取网页授权access_token
    public AccessTokenResponse getAccessToken(String code) {
        String url = WxConst.wxServiceUrl + "sns/oauth2/access_token?appid=" + wxConfig.getAppid() + "&secret=" + wxConfig.getAppsecret() + "&code=" + code + "&grant_type=authorization_code";
        String s = HttpUtil.get(url);
        AccessTokenResponse accessTokenResponse = JSONUtil.toBean(s, AccessTokenResponse.class);
        return accessTokenResponse;
    }


}
